package com.itheima.wechatweb;

import cn.hutool.core.lang.Assert;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.itheima.entity.Result;
import com.itheima.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * @version V1.0
 * @author: ljx
 * @date: 2020/02/10 16:58
 * @description:
 */
@RequestMapping("/imgCode")
@Controller
public class ImgCodeController {

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @Autowired
    RedisUtil redisUtil;

    @RequestMapping(value = "{deviceId}",method = RequestMethod.GET)
    public void getImgCode(@PathVariable String deviceId, HttpServletResponse response) throws IOException {
        Assert.notNull(deviceId, "机器码不能为空");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = defaultKaptcha.createText();
        //生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        //生成的验证码写入redis
        redisUtil.setex(deviceId,text,300);
        //获取输出流
        ServletOutputStream out = response.getOutputStream();
        //将图片写回浏览器
        ImageIO.write(image, "JPEG", out);
    }

}
